package com.neuedu.corejava.ch12;

import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

/**
 * 
 * @author myh
 * @version 2019年8月13日下午3:02:36
 *
 */
public class FileWatch {

	public static void main(String[] args) {
		Path path = Paths.get("C:/");
		try { /* 创建文件监控对象 */
			WatchService watchService = FileSystems.getDefault()
					.newWatchService(); /* 注册文件监控的所有事件类型 */
			path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
					StandardWatchEventKinds.ENTRY_DELETE,
					StandardWatchEventKinds.ENTRY_MODIFY);
			/* 循环监测文件 */
			File root = new File(path.toUri());
			while (true) {
				/* 迭代触发事件的所有文件 */
				WatchKey watchKey = watchService.take();
				for (WatchEvent<?> event : watchKey.pollEvents()) {
					System.out.println(event.context().toString() + " 事件类型："
							+ event.kind());

					long free = root.getFreeSpace();
					long total = root.getTotalSpace();
					long usable = root.getUsableSpace();

					System.out.println("C盘总容量：" + (total / 1024 / 1024));
					System.out.println("C盘已用空间："
							+ ((total - usable) / 1024 / 1024));
					System.out.println("C盘可用空间：" + (free / 1024 / 1024));
				}
				if (!watchKey.reset())
					return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
